package com.jcark.ui.view.textview;

import android.content.Context;
import android.content.res.TypedArray;
import android.text.Editable;
import android.text.InputFilter;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.DigitsKeyListener;
import android.util.AttributeSet;
import android.view.ActionMode;
import android.view.Menu;
import android.view.MenuItem;

import com.jcark.ui.R;
import com.jcark.ui.font.FontManager;

/**
 * 可替换原有大部分继承LimitEditText的view
 *
 * @author King.Zi<br>
 * @date 2022/01/13<br>
 * Email: 78688689@qq.com
 **/
public class MLimitEditTextView extends androidx.appcompat.widget.AppCompatEditText {
    private static final String STRING_DOT = ".";
    private static final String STRING_ZERO = "0";
    private int mTypeFaceValue;

    public MLimitEditTextView(Context context) {
        super(context);
    }

    public MLimitEditTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        getAttrs(context, attrs);
    }

    public MLimitEditTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        getAttrs(context, attrs);
    }

    private void getAttrs(Context context, AttributeSet attrs) {
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.MLimitEditTextView);
        mTypeFaceValue = typedArray.getInt(R.styleable.MLimitEditTextView_met_external_typeface, 0);
        init(context);
        typedArray.recycle();
    }

    private void init(Context context) {
        FontManager.getInstance().setTypeface(context, this, mTypeFaceValue);
    }

    /**
     * @param max    最大输入限制
     * @param digits
     */
    public void setTextWatcher(double max, int... digits) {
        if (digits.length > 0) {
            setFilters(new InputFilter[]{new MoneyValueFilter().setDigits(digits[0])});
        } else {
            setFilters(new InputFilter[]{new MoneyValueFilter()});
        }

        addTextChangedListener(new TextWatcher() {
            private String outStr = ""; //这个值存储输入超过两位数时候显示的内容

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                String edit = s.toString();
                if (edit.length() > 0 && Double.valueOf(edit) > 0) {
                    outStr = edit;
                }
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (!TextUtils.isEmpty(s)) {
                    if (Double.valueOf(s.toString()) > max && !TextUtils.isEmpty(outStr) && Double.valueOf(outStr) <= max) {
                        setText(outStr);
                        setSelection(outStr.length() - 1);
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    public class MoneyValueFilter extends DigitsKeyListener {

        private static final String TAG = "MoneyValueFilter";

        public MoneyValueFilter() {
            super(false, true);
        }

        private int digits = 2;

        public MoneyValueFilter setDigits(int d) {
            digits = d;
            return this;
        }

        @Override
        public CharSequence filter(CharSequence source, int start, int end,
                                   Spanned dest, int dstart, int dend) {
            CharSequence out = super.filter(source, start, end, dest, dstart, dend);

            // if changed, replace the source
            if (out != null) {
                source = out;
                start = 0;
                end = out.length();
            }

            int len = end - start;

            // if deleting, source is empty
            // and deleting can't break anything
            if (len == 0) {
                return source;
            }

            //以点开始的时候，自动在前面添加0
            if (STRING_DOT.equals(source.toString()) && dstart == 0) {
                return "0.";
            }
            //如果起始位置为0,且第二位跟的不是".",则无法后续输入
            if (!STRING_DOT.equals(source.toString()) && STRING_ZERO.equals(dest.toString())) {
                return "";
            }

            int dlen = dest.length();

            // Find the position of the decimal .
            for (int i = 0; i < dstart; i++) {
                if (dest.charAt(i) == '.') {
                    // being here means, that a number has
                    // been inserted after the dot
                    // check if the amount of digits is right
                    return (dlen - (i + 1) + len > digits) ?
                            "" :
                            new SpannableStringBuilder(source, start, end);
                }
            }

            for (int i = start; i < end; ++i) {
                if (source.charAt(i) == '.') {
                    // being here means, dot has been inserted
                    // check if the amount of digits is right
                    if ((dlen - dend) + (end - (i + 1)) > digits) {
                        return "";
                    } else {
                        break;  // return new SpannableStringBuilder(source, start, end);
                    }
                }
            }


            // if the dot is after the inserted part,
            // nothing can break
            return new SpannableStringBuilder(source, start, end);
        }
    }

    /**
     * 是否允许复制粘贴
     */
    public void cancelCopy() {
        setLongClickable(false);
        setTextIsSelectable(false);
        setCustomSelectionActionModeCallback(new ActionMode.Callback() {
            @Override
            public boolean onCreateActionMode(ActionMode mode, Menu menu) {
                return false;
            }

            @Override
            public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
                return false;
            }

            @Override
            public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
                return false;
            }

            @Override
            public void onDestroyActionMode(ActionMode mode) {

            }
        });
    }
}
